package com.uniview.web.contorller;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashSet;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.ServletRequestUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.uniview.base.BaseController;
import com.uniview.entity.po.Employees;
import com.uniview.entity.po.Menu;
import com.uniview.entity.po.ResourceRole;
import com.uniview.entity.vo.MenuRole;
import com.uniview.entity.vo.MenuVO;
import com.uniview.entity.vo.Pager;
import com.uniview.entity.vo.Query;
import com.uniview.entity.vo.QueryBuilder;
import com.uniview.entity.vo.ResultMessage;
import com.uniview.entity.vo.TableJsonVO;
import com.uniview.enums.EMatchMode;
import com.uniview.enums.EOrderMode;
import com.uniview.service.MenuService;
import com.uniview.service.RoleService;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

@Controller
@RequestMapping(value = "/sys")
public class MenuController extends BaseController {

	private Logger logger = Logger.getLogger(MenuController.class);

	@Autowired
	private MenuService menuService;

	@Autowired
	private RoleService roleService;

	@Value("#{configProperties['uniview.superAdmin']}")
	private String superAdmin;

	@RequestMapping(value = "/addMenuView")
	public ModelAndView addMenuView(HttpServletRequest request, HttpServletResponse response) {
		ModelAndView view = new ModelAndView("views/sys/menuAdd");
		String basePath = request.getServletContext().getContextPath();
		view.addObject("basePath", basePath);
		return view;
	}

	@RequestMapping(value = "/updateMenuView")
	public ModelAndView updateMenuView(HttpServletRequest request, HttpServletResponse response) {
		ModelAndView view = new ModelAndView("views/sys/menuUpdate");
		String basePath = request.getServletContext().getContextPath();
		view.addObject("basePath", basePath);
		return view;
	}

	@RequestMapping(value = "/saveMenu")
	@ResponseBody
	public ResultMessage saveMenu(HttpServletRequest request) {
		try {
			String menuName = ServletRequestUtils.getStringParameter(request, "menuName");
			String menuUrl = ServletRequestUtils.getStringParameter(request, "menuUrl", "");
			String menuIcon = ServletRequestUtils.getStringParameter(request, "menuIcon", "");
			int menuType = ServletRequestUtils.getIntParameter(request, "menuType", 0);
			int menuSort = ServletRequestUtils.getIntParameter(request, "menuSort", 1);
			int parentId = ServletRequestUtils.getIntParameter(request, "parentId", -1);
			int disabled = ServletRequestUtils.getIntParameter(request, "disabled", 0);

			Menu menus = new Menu();
			menus.setMenuName(menuName);
			menus.setMenuUrl(menuUrl);
			menus.setMenuIcon(menuIcon);
			menus.setMenuType(menuType);
			menus.setMenuSort(menuSort);
			if (parentId > 0) {
				menus.setParentId(parentId);
			}
			menus.setDisabled(disabled);
			menus.setCreated(new Date());
			menus.setModified(new Date());

			int result = menuService.addMenu(menus);
			if (result > 0) {
				return getResult("保存成功", true, result);
			}
		} catch (Exception e) {
			logger.error("新增菜单异常", e);
		}
		return getResult("保存失败", false);
	}

	@RequestMapping(value = "menu")
	public ModelAndView getMenuView(HttpServletRequest request, HttpServletResponse response) {
		ModelAndView view = new ModelAndView("menu/menu");
		String basePath = request.getServletContext().getContextPath();
		view.addObject("basePath", basePath);
		return view;
	}

	/**
	 * 分页查询
	 * 
	 * @param request
	 * @param page
	 * @param limit
	 * @param menuName
	 * @return
	 */
	@RequestMapping(value = "findMenuByPage")
	@ResponseBody
	public TableJsonVO findMenyByPage(HttpServletRequest request, Integer page, Integer limit, String menuName) {
		QueryBuilder queryBuilder = new QueryBuilder(Menu.class.getName());
		Query query = new Query("menuName", EMatchMode.LIKE, menuName);
		queryBuilder.add(query);
		queryBuilder.setOrderCols("modified");
		queryBuilder.setOrderMode(EOrderMode.DESC);
		Pager<Menu> pager = menuService.findMenuByPager(queryBuilder, limit, page);
		List<Menu> menuList = pager.getPagerList();
		Integer count = pager.getTotalRow();
//		return getTableJsonString(JsonMapper.toJsonString(menuList), count);
		return getTableJsonVO(menuList, count);
	}

	@RequestMapping(value = "getAllMenu")
	@ResponseBody
	public ResultMessage getAllMenu(HttpServletRequest request, HttpServletResponse response) {
		Employees emp = (Employees) request.getSession().getAttribute("employees");
		return getResult("", true, this.findAllMenu(emp));
	}

	@RequestMapping(value = "getMenuInfo")
	public ModelAndView getMenuInfo(HttpServletRequest request, HttpServletResponse response) {
		int menuId = ServletRequestUtils.getIntParameter(request, "menuId", -1);
		ModelAndView view = new ModelAndView("menu/updateMenuInfo");
		Menu menu = menuService.findMenuById(menuId); // 获取菜单信息
		view.addObject("menu", menu);
		List<Menu> parentList = menuService.findParentMenu(null);
		view.addObject("parentMenu", parentList);
		return view;
	}

	@RequestMapping(value = "getAddMenuView")
	public ModelAndView getAddMenuView(HttpServletRequest request, HttpServletResponse response) {
		ModelAndView view = new ModelAndView("menu/addMenuInfo");
		List<Menu> parentList = menuService.findParentMenu(null);
		view.addObject("parentMenu", parentList);
		return view;
	}

	/**
	 * 获取所有的菜单(暂无权限)
	 * 
	 * @return
	 */
	public List<MenuVO> findAllMenu(Employees emp) {
		// Employees emp = (Employees)
		// request.getSession().getAttribute("employees");
		if (null != emp) {
			List<ResourceRole> resourceRoles = roleService.findReousceRoleByUserId(emp.getEmpCode() + "");
			if (null != resourceRoles && !resourceRoles.isEmpty()) {
				List<Menu> menus = new ArrayList<Menu>();
				for (ResourceRole rr : resourceRoles) {
					List<MenuRole> mrs = menuService.findMenuWithRoleId(rr.getRoleId());
					for (MenuRole mr : mrs) {
						Menu menu = menuService.findMenuById(mr.getMenuId());
						if (menu.getParentId() == null || menu.getParentId() <= 0) {
							menus.add(menu);
						}
					}
				}
				return this.setChindrenMenu(menus, resourceRoles);
			} else {
				List<Menu> menus = menuService.findAllMenu();
				// 查找所有的子集节点
				return this.setChindrenMenu(menus);
			}
		} else {
			List<Menu> menus = menuService.findAllMenu();
			// 查找所有的子集节点
			return this.setChindrenMenu(menus);
		}
	}

	/**
	 * 查找菜单下面的所有子菜单
	 * 
	 * @param childrenMenu
	 */
	public List<MenuVO> setChindrenMenu(List<Menu> childrenMenu) {
		List<MenuVO> list = new ArrayList<MenuVO>();
		if (!childrenMenu.isEmpty() && childrenMenu.size() > 0) {
			for (Menu cm : childrenMenu) {
				MenuVO mvo = new MenuVO(cm.getMenuName(), cm.getMenuId());
				List<Menu> tempCm = menuService.findMenuByParentId(cm.getMenuId());
				List<MenuVO> cList = new ArrayList<MenuVO>();
				if (null != tempCm && tempCm.size() > 0) {
					for (Menu tcm : tempCm) {
						MenuVO tempMvo = new MenuVO(tcm.getMenuName(), tcm.getMenuId());
						cList.add(tempMvo);
					}
				}
				mvo.setNodes(cList);
				list.add(mvo);
			}
		}
		return list;
	}

	/**
	 * 查找菜单下面的所有子菜单
	 * 
	 * @param childrenMenu
	 */
	public List<MenuVO> setChindrenMenu(List<Menu> childrenMenu, List<ResourceRole> resourceRoles) {
		List<MenuVO> list = new ArrayList<MenuVO>();
		if (!childrenMenu.isEmpty() && childrenMenu.size() > 0) {
			for (Menu cm : childrenMenu) {
				MenuVO mvo = new MenuVO(cm.getMenuName(), cm.getMenuId());
				List<Menu> tempCm = menuService.findMenuByParentId(cm.getMenuId());
				List<MenuVO> cList = new ArrayList<MenuVO>();
				if (null != tempCm && tempCm.size() > 0) {
					for (int i = 0; i < tempCm.size(); i++) {
						for (int j = 0; j < resourceRoles.size(); j++) {
							if (tempCm.get(i).getMenuId() == resourceRoles.get(j).getMenuId()) {
								MenuVO tempMvo = new MenuVO(tempCm.get(i).getMenuName(), tempCm.get(i).getMenuId());
								cList.add(tempMvo);
							}
						}
					}
				}
				mvo.setNodes(cList);
				list.add(mvo);
			}
		}
		return list;
	}

	@RequestMapping(value = "updateMenu")
	@ResponseBody
	public ResultMessage updateMenu(HttpServletRequest request) {
		try {
			String menuName = ServletRequestUtils.getStringParameter(request, "menuName");
			String menuUrl = ServletRequestUtils.getStringParameter(request, "menuUrl", "");
			String menuIcon = ServletRequestUtils.getStringParameter(request, "menuIcon", "");
			int menuType = ServletRequestUtils.getIntParameter(request, "menuType", 0);
			int menuSort = ServletRequestUtils.getIntParameter(request, "menuSort", 1);
			int parentId = ServletRequestUtils.getIntParameter(request, "parentId", -1);
			int disabled = ServletRequestUtils.getIntParameter(request, "disabled", 0);
			String created = ServletRequestUtils.getStringParameter(request, "created");
			int menuId = ServletRequestUtils.getIntParameter(request, "menuId");

			Menu menus = new Menu();
			menus.setMenuId(menuId);
			menus.setMenuName(menuName);
			menus.setMenuUrl(menuUrl);
			menus.setMenuIcon(menuIcon);
			menus.setMenuType(menuType);
			menus.setMenuSort(menuSort);
			if (parentId > 0) {
				menus.setParentId(parentId);
			}
			menus.setDisabled(disabled);
			SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			menus.setCreated(sdf.parse(created));
			menus.setModified(new Date());

			boolean result = menuService.updateMenu(menus);
			if (result) {
				return getResult("更新成功", true);
			}
		} catch (Exception e) {
			logger.error("更新菜单信息异常", e);
		}
		return getResult("更新失败", false);
	}

	@RequestMapping(value = "deleteMenu")
	@ResponseBody
	public ResultMessage deletMenuById(HttpServletRequest request, Integer menuId) {
		try {
			boolean result = menuService.deleteMenu(menuId);
			if (result) {
				return getResult("删除菜单成功", true);
			}
		} catch (Exception e) {
			logger.error("删除菜单异常", e);
		}
		return getResult("删除菜单失败", false);
	}

	/**
	 * 获取所有的父菜单
	 * 
	 * @param request
	 * @return
	 */
	@RequestMapping(value = "getParentMenuByType")
	@ResponseBody
	public JSONObject getAllParentMenu(HttpServletRequest request, Integer menuType) {
		if (menuType == null) {
			menuType = 1;
		}
		JSONObject obj = new JSONObject();
		try {
			List<Menu> list = menuService.findParentMenu(menuType);
			obj.put("data", list);
		} catch (Exception e) {
			logger.error("获取父菜单异常.......getAllParentMenu", e);
		}
		return obj;
	}

	/**
	 * 修改/新增菜单
	 * 
	 * @param request
	 * @param menu
	 * @return
	 */
	@RequestMapping(value = "/addOrUpdateMenu")
	@ResponseBody
	public ResultMessage addMenu(HttpServletRequest request, Menu menu) {
		try {
			if (menu.getParentId() == 0) {
				menu.setParentId(null);
			}
			menu.setModified(new Date());
			Integer count = menuService.findMenuCountByCondition(menu.getMenuName(), menu.getMenuId());
			if (menu.getMenuId() == 0) {// 新增
				menu.setCreated(new Date());
				if (count > 0) {
					return getResult("菜单名称已存在", false);
				}
				menuService.addMenu(menu);
			} else if (menu.getMenuId() > 0) {// 修改
				Menu obj = menuService.findMenuById(menu.getMenuId());
				if (count <= 1) {
					menu.setCreated(obj.getCreated());
					menuService.updateMenu(menu);
				} else {
					return getResult("菜单名称已存在", false);
				}
			}
			return getResult("保存成功", true);
		} catch (Exception e) {
			logger.error("保存菜单异常", e);
		}
		return getResult("保存失败", false);
	}

	/**
	 * 根据id查询
	 * 
	 * @param request
	 * @param menuId
	 * @return
	 */
	@RequestMapping(value = "/findMenuById")
	@ResponseBody
	public Menu addMenu(HttpServletRequest request, Integer menuId) {
		return menuService.findMenuById(menuId);
	}

	/**
	 * 根据用户ID获取对应角色权限菜单
	 * 
	 * @param employeeId
	 * @return
	 */
	@RequestMapping(value = "/findMenuByUserId")
	@ResponseBody
	public JSONObject findMenuByUserRoleAuth(String empCode) {
		JSONObject result = new JSONObject();
		try {
			JSONArray lfetRowArray = new JSONArray();
			// 授权的子菜单
			// List<Menu> subList = menuService.findMenuByEmployeeId(empCode);
			List<Menu> subList = null;
			if (this.superAdmin.equalsIgnoreCase(empCode)) {
				subList = menuService.findAllClid();
			} else {
				subList = menuService.findMenuByEmployeeId(empCode);
			}
			subList = removeDuplicate(subList);
			// 所有的左侧父级菜单
			List<Menu> AllLeftParentList = menuService.findParentMenu(1);
			// 授权的左侧父级菜单
			List<Menu> authedLeftParentLsit = new ArrayList<Menu>();
			for (Menu menuP : AllLeftParentList) {
				for (Menu menuS : subList) {
					if (menuS.getParentId() != null && menuS.parentId == menuP.menuId) {
						authedLeftParentLsit.add(menuP);
						break;
					}
				}
			}
			for (Menu authedP : authedLeftParentLsit) {
				JSONObject row = new JSONObject();
				JSONObject parentObj = new JSONObject();
				parentObj.put("menuId", authedP.getMenuId());
				parentObj.put("menuName", authedP.getMenuName());
				parentObj.put("menuUrl", authedP.getMenuUrl());
				parentObj.put("menuIcon", authedP.getMenuIcon());
				row.put("parent", parentObj);
				JSONArray subRow = new JSONArray();
				for (Menu menuS : subList) {
					if (menuS.getParentId() == authedP.getMenuId()) {
						JSONObject subObj = new JSONObject();
						subObj.put("menuId", menuS.getMenuId());
						subObj.put("menuName", menuS.getMenuName());
						subObj.put("menuUrl", menuS.getMenuUrl());
						subObj.put("menuIcon", menuS.getMenuIcon());
						subRow.add(subObj);
					}
				}
				row.put("sub", subRow);
				lfetRowArray.add(row);
			}

			result.put("leftData", lfetRowArray);

			JSONArray topRowArray = new JSONArray();
			// 所有的顶部父级菜单
			List<Menu> AllTopParentList = menuService.findParentMenu(2);
			// 授权的顶部父级菜单
			List<Menu> authedTopParentLsit = new ArrayList<Menu>();
			for (Menu menuP : AllTopParentList) {
				for (Menu menuS : subList) {
					if (menuS.getParentId() != null && menuS.parentId == menuP.menuId) {
						authedTopParentLsit.add(menuP);
						break;
					}
				}
			}
			for (Menu authedP : authedTopParentLsit) {
				JSONObject row = new JSONObject();
				JSONObject parentObj = new JSONObject();
				parentObj.put("menuId", authedP.getMenuId());
				parentObj.put("menuName", authedP.getMenuName());
				parentObj.put("menuUrl", authedP.getMenuUrl());
				row.put("parent", parentObj);
				JSONArray subRow = new JSONArray();
				for (Menu menuS : subList) {
					if (menuS.getParentId() == authedP.getMenuId()) {
						JSONObject subObj = new JSONObject();
						subObj.put("menuId", menuS.getMenuId());
						subObj.put("menuName", menuS.getMenuName());
						subObj.put("menuUrl", menuS.getMenuUrl());
						subRow.add(subObj);
					}
				}
				row.put("sub", subRow);
				topRowArray.add(row);
			}
			result.put("topData", topRowArray);
			return result;
		} catch (Exception e) {
			e.printStackTrace();
		}
		return new JSONObject();
	}

	@SuppressWarnings("unchecked")
	public static List removeDuplicate(List list) {
		HashSet h = new HashSet(list);
		list.clear();
		list.addAll(h);
		return list;
	}

}
